<template>
  <div class="video-player-page">
    <!-- 顶部导航 -->
    <div class="video-header">
      <div class="header-left">
        <el-button @click="goBack" size="large" type="primary">
          <el-icon><ArrowLeft /></el-icon>
          {{ isNewWindow ? '关闭窗口' : '返回文件列表' }}
        </el-button>
      </div>
      <div class="header-center">
        <h1 class="video-title">{{ videoInfo?.fileName || '视频播放' }}</h1>
      </div>
      <div class="header-right">
        <el-button v-if="hasVideoList && randomMode" @click="playNextVideo" type="success">
          <el-icon><VideoCameraFilled /></el-icon>
          下一个随机视频
        </el-button>
      </div>
    </div>

    <!-- 视频播放区域 -->
    <div class="video-content" v-if="videoInfo">
      <!-- 视频播放器 -->
      <div class="video-wrapper">
        <video
          ref="videoRef"
          :src="videoUrl"
          controls
          preload="metadata"
          playsinline
          class="video-player"
          @loadstart="onLoadStart"
          @loadedmetadata="onLoadedMetadata"
          @canplay="onCanPlay"
          @error="onError"
          @timeupdate="onTimeUpdate"
          @ended="onVideoEnded"
        >
          您的浏览器不支持视频播放。
        </video>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>加载中...</p>
        </div>
        
        <!-- 错误状态 -->
        <div v-if="error" class="error-overlay">
          <el-icon><WarningFilled /></el-icon>
          <p>{{ error }}</p>
        </div>
      </div>

      <!-- 视频信息和控制面板 -->
      <div class="video-info-panel" v-if="!loading && !error">
        <!-- 刮削信息 -->
        <div v-if="videoInfo.title || videoInfo.code || videoInfo.performer" class="scraper-info">
          <div v-if="videoInfo.title" class="scraper-title">
            {{ videoInfo.title }}
          </div>
          <div class="scraper-meta">
            <el-tag v-if="videoInfo.code" size="large" type="primary" class="meta-tag">
              {{ videoInfo.code }}
            </el-tag>
            <el-tag v-if="videoInfo.performer" size="large" type="success" class="meta-tag">
              {{ videoInfo.performer }}
            </el-tag>
          </div>
        </div>

        <!-- 视频信息 -->
        <div class="video-info">
          <div class="info-grid">
            <div class="info-item">
              <span class="label">文件名:</span>
              <span class="value">{{ videoInfo.fileName }}</span>
            </div>
            <div class="info-item">
              <span class="label">文件大小:</span>
              <span class="value">{{ videoInfo.fileSizeReadable }}</span>
            </div>
            <div class="info-item">
              <span class="label">文件类型:</span>
              <span class="value">{{ videoInfo.fileType.toUpperCase() }}</span>
            </div>
            <div class="info-item">
              <span class="label">文件路径:</span>
              <span class="value" :title="videoInfo.filePath">{{ videoInfo.filePath }}</span>
            </div>
          </div>
        </div>

        <!-- 播放控制面板 -->
        <div class="player-controls">
          <div class="time-info">
            <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
            <div class="skip-time-setting">
              <span class="label">跳转:</span>
              <el-input-number 
                v-model="skipTime" 
                :min="1" 
                :max="60" 
                :step="5"
                size="small" 
                style="width: 80px"
              />
              <span class="unit">秒</span>
            </div>
          </div>
          
          <div class="controls">
            <el-button size="large" @click="skipBackward" :title="`快退${skipTime}秒 (←)`">
              <el-icon><ArrowLeft /></el-icon>
              -{{ skipTime }}s
            </el-button>
            <el-button size="large" @click="togglePlay" title="播放/暂停 (空格)">
              <el-icon>
                <VideoPlay v-if="paused" />
                <VideoPause v-else />
              </el-icon>
              {{ paused ? '播放' : '暂停' }}
            </el-button>
            <el-button size="large" @click="skipForward" :title="`快进${skipTime}秒 (→)`">
              <el-icon><ArrowRight /></el-icon>
              +{{ skipTime }}s
            </el-button>
            <el-button size="large" @click="toggleMute" title="静音/取消静音 (M)">
              <el-icon>
                <Mute />
              </el-icon>
              {{ muted ? '取消静音' : '静音' }}
            </el-button>
            <el-button size="large" @click="toggleFullscreen" title="全屏 (F)">
              <el-icon><FullScreen /></el-icon>
              全屏
            </el-button>
            <div class="playback-speed-setting">
              <span class="label">速度:</span>
              <el-select v-model="playbackSpeed" size="large" style="width: 90px" @change="onPlaybackSpeedChange">
                <el-option label="0.5x" :value="0.5" />
                <el-option label="0.75x" :value="0.75" />
                <el-option label="1.0x" :value="1.0" />
                <el-option label="1.25x" :value="1.25" />
                <el-option label="1.5x" :value="1.5" />
                <el-option label="2.0x" :value="2.0" />
              </el-select>
            </div>
          </div>
        </div>

        <!-- 快捷键说明 -->
        <div class="shortcuts-info">
          <el-text size="small" type="info">
            快捷键: ← 快退{{ skipTime }}s | → 快进{{ skipTime }}s | ↑ 增加音量 | ↓ 减少音量 | 空格 播放/暂停 | M 静音 | F/回车 全屏 | [ 减速0.25x | ] 加速0.25x | 播放速度: {{ playbackSpeed }}x
          </el-text>
        </div>
      </div>
    </div>

    <!-- 无视频信息状态 -->
    <div v-else class="no-video">
      <el-empty description="找不到视频信息">
        <el-button type="primary" @click="goBack">返回文件列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, ArrowRight, Loading, WarningFilled, VideoPlay, VideoPause, 
  Mute, FullScreen, VideoCameraFilled 
} from '@element-plus/icons-vue'
import { fileManagerApi, type FileIndexVO } from '@/modules/file/api/fileManager.ts'

interface Props {
  id: string
}

const props = defineProps<Props>()
const route = useRoute()
const router = useRouter()

// 响应式数据
const videoRef = ref<HTMLVideoElement>()
const loading = ref(false)
const error = ref('')
const currentTime = ref(0)
const duration = ref(0)
const paused = ref(true)
const muted = ref(false)
const progressSaveTimer = ref<any>(null)
const lastSavedTime = ref(0)
const videoInfo = ref<FileIndexVO | null>(null)

// 播放速度设置（从 localStorage 读取）
const PLAYBACK_SPEED_KEY = 'video_playback_speed'
const playbackSpeed = ref<number>(getStoredPlaybackSpeed())

// 随机播放相关
const randomMode = ref(false)
const videoList = ref<FileIndexVO[]>([])

// 计算属性
const videoUrl = computed(() => {
  if (!videoInfo.value) return ''
  return fileManagerApi.getStreamUrl(videoInfo.value.id)
})

const hasVideoList = computed(() => {
  return videoList.value.length > 1
})

const isNewWindow = computed(() => {
  return !!window.opener
})

// 获取视频信息
const getVideoInfo = async (videoId: string) => {
  loading.value = true
  error.value = ''
  
  try {
    // 从路由查询参数获取相关信息
    const query = route.query
    randomMode.value = query.random === 'true'
    
    // 处理视频列表（随机播放模式）
    if (query.videoList) {
      try {
        videoList.value = JSON.parse(query.videoList as string)
        console.log('解析到视频列表，数量:', videoList.value.length)
      } catch (e) {
        console.warn('解析视频列表失败:', e)
      }
    }
    
    // 如果有视频列表，从中查找当前视频
    if (videoList.value.length > 0) {
      const found = videoList.value.find(v => v.id === videoId)
      if (found) {
        videoInfo.value = found
        console.log('从视频列表中找到视频信息:', found.fileName)
        return
      }
    }
    
    // 使用文件详情API获取视频信息
    console.log('调用文件详情API获取视频信息, ID:', videoId)
    const fileDetail = await fileManagerApi.getFileDetail(videoId)
    videoInfo.value = fileDetail
    console.log('通过文件详情API获取视频信息:', fileDetail.fileName)
  } catch (err) {
    console.error('获取视频信息失败:', err)
    error.value = '获取视频信息失败'
  } finally {
    loading.value = false
  }
}

// 监听 videoInfo 变化
watch(() => videoInfo.value, async (newInfo) => {
  if (newInfo) {
    resetPlayer()
    // 不在这里加载进度，等待视频元数据加载完成后统一处理
  }
}, { immediate: true })

// 键盘事件状态管理
let isFullscreen = ref(false)
let processingKey = false  // 是否正在处理按键
const keyExecutionMap = new Map<string, number>()  // 记录每个按键的最后执行时间
const KEY_DEBOUNCE_TIME = 200  // 200ms内的相同按键视为重复
// 不需要防抖的按键列表（快进快退可以连续触发）
const NO_DEBOUNCE_KEYS = ['ArrowLeft', 'ArrowRight']

// 检测全屏状态变化
const updateFullscreenState = () => {
  isFullscreen.value = !!(
    document.fullscreenElement ||
    (document as any).webkitFullscreenElement ||
    (document as any).mozFullScreenElement ||
    (document as any).msFullscreenElement
  )
}

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (!videoRef.value || !videoInfo.value) return

  // 防止在输入框等元素中触发
  const target = event.target as HTMLElement
  if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return

  // 快进快退键不需要防抖，可以连续触发
  const needDebounce = !NO_DEBOUNCE_KEYS.includes(event.code)

  // 如果正在处理按键，且该按键需要防抖，直接拦截
  if (processingKey && needDebounce) {
    console.log('正在处理按键，忽略重复事件')
    event.preventDefault()
    event.stopPropagation()
    event.stopImmediatePropagation()
    return
  }

  // 检查该按键是否在防抖时间内（快进快退键跳过此检查）
  if (needDebounce) {
    const now = Date.now()
    const lastExecutionTime = keyExecutionMap.get(event.code) || 0
    if (now - lastExecutionTime < KEY_DEBOUNCE_TIME) {
      console.log(`按键 ${event.code} 在防抖时间内，忽略。距离上次: ${now - lastExecutionTime}ms`)
      event.preventDefault()
      event.stopPropagation()
      event.stopImmediatePropagation()
      return
    }
    keyExecutionMap.set(event.code, now)
  }

  // 设置处理标志（快进快退键跳过此标志）
  if (needDebounce) {
    processingKey = true
  }

  // 阻止事件冒泡和默认行为
  event.preventDefault()
  event.stopPropagation()
  event.stopImmediatePropagation()

  console.log(`执行按键操作: ${event.code}`)

  try {
    switch (event.code) {
      case 'ArrowLeft':
        skipBackward()
        break
      case 'ArrowRight':
        skipForward()
        break
      case 'ArrowUp':
        increaseVolume()
        break
      case 'ArrowDown':
        decreaseVolume()
        break
      case 'Space':
        togglePlay()
        break
      case 'KeyF':
      case 'Enter':
        toggleFullscreen()
        break
      case 'KeyM':
        toggleMute()
        break
      case 'BracketLeft':
        decreasePlaybackSpeed()
        break
      case 'BracketRight':
        increasePlaybackSpeed()
        break
    }
  } finally {
    // 使用 setTimeout 确保在下一个事件循环才重置标志（快进快退键跳过）
    if (needDebounce) {
      setTimeout(() => {
        processingKey = false
      }, 50)
    }
  }
}


// 保存进度并清理资源
const saveProgressAndCleanup = async () => {
  // 保存当前播放进度
  if (videoInfo.value && currentTime.value > 0 && duration.value > 0) {
    console.log('正在保存播放进度:', currentTime.value)
    
    try {
      // 优先使用常规的异步请求，因为sendBeacon有Content-Type限制
      const savePromise = fileManagerApi.saveVideoProgress({
        fileId: videoInfo.value.id,
        currentTime: currentTime.value,
        duration: duration.value
      })
      
      // 如果支持sendBeacon且在页面卸载过程中，使用备用方案
      if (navigator.sendBeacon && document.visibilityState === 'hidden') {
        // sendBeacon只支持特定的Content-Type，需要使用FormData
        const formData = new FormData()
        formData.append('data', JSON.stringify({
          fileId: videoInfo.value.id,
          currentTime: currentTime.value,
          duration: duration.value
        }))
        navigator.sendBeacon('/api/file/progress/save-beacon', formData)
      } else {
        // 正常情况下使用异步请求
        await savePromise
      }
      
      console.log('播放进度保存成功')
    } catch (error) {
      console.warn('保存播放进度失败:', error)
      
      // 最后的降级方案：同步XMLHttpRequest
      try {
        const xhr = new XMLHttpRequest()
        xhr.open('POST', '/api/file/progress/save', false) // 同步请求
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify({
          fileId: videoInfo.value.id,
          currentTime: currentTime.value,
          duration: duration.value
        }))
        console.log('使用同步请求保存进度成功')
      } catch (syncError) {
        console.error('同步保存进度也失败:', syncError)
      }
    }
  }
}

// 页面关闭前保存进度
const handleBeforeUnload = () => {
  console.log('页面即将关闭，保存播放进度')
  saveProgressAndCleanup()
  // 不阻止页面关闭
}

// 页面可见性变化时保存进度
const handleVisibilityChange = () => {
  if (document.visibilityState === 'hidden') {
    console.log('页面变为隐藏状态，保存播放进度')
    saveProgressAndCleanup()
  }
}

// 页面失去焦点时保存进度
const handlePageHide = () => {
  console.log('页面失去焦点，保存播放进度')
  saveProgressAndCleanup()
}

// 组件挂载时绑定事件
onMounted(() => {
  // 绑定键盘事件，使用 capture 模式确保优先处理
  document.addEventListener('keydown', handleKeyDown, { capture: true })
  
  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', updateFullscreenState)
  document.addEventListener('webkitfullscreenchange', updateFullscreenState)
  document.addEventListener('mozfullscreenchange', updateFullscreenState)
  document.addEventListener('MSFullscreenChange', updateFullscreenState)
  
  // 监听页面关闭相关事件
  window.addEventListener('beforeunload', handleBeforeUnload)
  window.addEventListener('pagehide', handlePageHide)
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  // 初始化全屏状态
  updateFullscreenState()
  
  // 获取视频信息
  getVideoInfo(props.id)
})

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
  // 保存进度
  saveProgressAndCleanup()
  
  // 清理播放进度保存定时器
  if (progressSaveTimer.value) {
    clearTimeout(progressSaveTimer.value)
  }
  
  // 清理跳转消息显示定时器
  if (skipMessageTimeout) {
    clearTimeout(skipMessageTimeout)
  }
  
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown, { capture: true })
  
  // 移除全屏状态监听
  document.removeEventListener('fullscreenchange', updateFullscreenState)
  document.removeEventListener('webkitfullscreenchange', updateFullscreenState)
  document.removeEventListener('mozfullscreenchange', updateFullscreenState)
  document.removeEventListener('MSFullscreenChange', updateFullscreenState)
  
  // 移除页面关闭监听
  window.removeEventListener('beforeunload', handleBeforeUnload)
  window.removeEventListener('pagehide', handlePageHide)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 重置播放器状态
const resetPlayer = () => {
  loading.value = false
  error.value = ''
  currentTime.value = 0
  duration.value = 0
  paused.value = true
  muted.value = false
}

// 视频事件处理
const onLoadStart = () => {
  loading.value = true
  error.value = ''
}

const onLoadedMetadata = async () => {
  if (videoRef.value) {
    duration.value = videoRef.value.duration || 0
    // 先恢复播放进度，再自动播放
    await restoreProgress()
  }
}

const onCanPlay = () => {
  loading.value = false
  // 设置播放速度
  applyPlaybackSpeed()
  // 自动播放视频
  autoPlay()
}

const onError = (event: Event) => {
  loading.value = false
  const target = event.target as HTMLVideoElement
  let errorMessage = '视频加载失败'
  
  if (target.error) {
    switch (target.error.code) {
      case target.error.MEDIA_ERR_ABORTED:
        errorMessage = '视频加载被中断'
        break
      case target.error.MEDIA_ERR_NETWORK:
        errorMessage = '网络错误，无法加载视频'
        break
      case target.error.MEDIA_ERR_DECODE:
        errorMessage = '视频解码错误'
        break
      case target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMessage = '不支持的视频格式'
        break
      default:
        errorMessage = '未知错误'
    }
  }
  
  error.value = errorMessage
  ElMessage.error(errorMessage)
}

const onTimeUpdate = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime
    paused.value = videoRef.value.paused
    muted.value = videoRef.value.muted
    
    // 定时保存播放进度（避免频繁保存）
    saveProgressThrottled()
  }
}

const onVideoEnded = () => {
  clearProgress()
  // 如果开启了随机模式且有视频列表，自动播放下一个随机视频
  if (randomMode.value && hasVideoList.value) {
    playNextRandomVideo()
  }
}

// 播放控制
const togglePlay = () => {
  if (!videoRef.value) return
  
  if (videoRef.value.paused) {
    videoRef.value.play().catch(err => {
      console.error('播放失败:', err)
      ElMessage.error('播放失败')
    })
  } else {
    videoRef.value.pause()
  }
}

const toggleMute = () => {
  if (!videoRef.value) return
  videoRef.value.muted = !videoRef.value.muted
}

// 增加音量
const increaseVolume = () => {
  if (!videoRef.value) return

  const currentVolume = videoRef.value.volume
  const newVolume = Math.min(1, currentVolume + 0.1)
  videoRef.value.volume = newVolume

  // 如果是静音状态，自动取消静音
  if (videoRef.value.muted) {
    videoRef.value.muted = false
  }

  console.log('音量增加到:', Math.round(newVolume * 100) + '%')

  ElMessage({
    message: `音量: ${Math.round(newVolume * 100)}%`,
    type: 'info',
    duration: 800,
    showClose: false,
    grouping: true
  })
}

// 减少音量
const decreaseVolume = () => {
  if (!videoRef.value) return

  const currentVolume = videoRef.value.volume
  const newVolume = Math.max(0, currentVolume - 0.1)
  videoRef.value.volume = newVolume

  console.log('音量减少到:', Math.round(newVolume * 100) + '%')

  ElMessage({
    message: `音量: ${Math.round(newVolume * 100)}%`,
    type: 'info',
    duration: 800,
    showClose: false,
    grouping: true
  })
}

const toggleFullscreen = () => {
  if (!videoRef.value) return

  if (videoRef.value.requestFullscreen) {
    videoRef.value.requestFullscreen()
  } else {
    ElMessage.warning('浏览器不支持全屏模式')
  }
}

// 跳转时间设置
const skipTime = ref(10)

// 消息显示定时器
let skipMessageTimeout: any = null

// 快退（左箭头键）
const skipBackward = () => {
  if (!videoRef.value || !duration.value) return

  const currentTimeBeforeSkip = videoRef.value.currentTime
  const newTime = Math.max(0, currentTimeBeforeSkip - skipTime.value)
  const actualSkip = currentTimeBeforeSkip - newTime

  console.log('执行快退操作，从', currentTimeBeforeSkip, '到', newTime, '实际跳转:', actualSkip)

  // 确保实际有跳转才更新
  if (actualSkip > 0.1) {
    videoRef.value.currentTime = newTime

    // 清除之前的消息定时器
    if (skipMessageTimeout) {
      clearTimeout(skipMessageTimeout)
    }

    // 延迟显示消息，如果频繁操作则只显示最后一次
    skipMessageTimeout = setTimeout(() => {
      ElMessage({
        message: `快退 ${actualSkip.toFixed(0)} 秒`,
        type: 'info',
        duration: 800,
        showClose: false,
        grouping: true
      })
    }, 200)
  }
}

// 快进（右箭头键）
const skipForward = () => {
  if (!videoRef.value || !duration.value) return

  const currentTimeBeforeSkip = videoRef.value.currentTime
  const newTime = Math.min(duration.value, currentTimeBeforeSkip + skipTime.value)
  const actualSkip = newTime - currentTimeBeforeSkip

  console.log('执行快进操作，从', currentTimeBeforeSkip, '到', newTime, '实际跳转:', actualSkip)

  // 确保实际有跳转才更新
  if (actualSkip > 0.1) {
    videoRef.value.currentTime = newTime

    // 清除之前的消息定时器
    if (skipMessageTimeout) {
      clearTimeout(skipMessageTimeout)
    }

    // 延迟显示消息，如果频繁操作则只显示最后一次
    skipMessageTimeout = setTimeout(() => {
      ElMessage({
        message: `快进 ${actualSkip.toFixed(0)} 秒`,
        type: 'info',
        duration: 800,
        showClose: false,
        grouping: true
      })
    }, 200)
  }
}

// 格式化时间
const formatTime = (seconds: number): string => {
  if (isNaN(seconds) || seconds < 0) return '00:00'
  
  const hrs = Math.floor(seconds / 3600)
  const mins = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hrs > 0) {
    return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
}

// 加载播放进度 - 已移除，统一在 restoreProgress 中处理

// 恢复播放进度
const restoreProgress = async () => {
  if (!videoInfo.value || !videoRef.value) return
  
  try {
    console.log('正在恢复播放进度, currentTime:', videoInfo.value.currentTime)
    
    // 从文件详情中获取播放进度信息
    if (videoInfo.value.currentTime && videoInfo.value.currentTime > 0 && videoInfo.value.currentTime < duration.value * 0.95) {
      videoRef.value.currentTime = videoInfo.value.currentTime
      ElMessage.success(`已恢复到上次播放位置: ${formatTime(videoInfo.value.currentTime)}`)
      console.log('已恢复播放进度到:', videoInfo.value.currentTime)
    } else {
      console.log('无需恢复播放进度')
    }
    
    // 等待进度恢复完成后再自动播放
    await new Promise(resolve => setTimeout(resolve, 200))
    
  } catch (error) {
    console.warn('恢复播放进度失败:', error)
  }
}

// 自动播放视频
const autoPlay = async () => {
  if (!videoRef.value) return
  
  try {
    // 等待一下确保播放器准备就绪
    await new Promise(resolve => setTimeout(resolve, 100))
    
    await videoRef.value.play()
    console.log('视频自动播放成功')
  } catch (error) {
    console.warn('自动播放失败，可能被浏览器阻止:', error)
    // 如果自动播放失败，显示提示让用户手动点击播放
    ElMessage.warning('请点击播放按钮开始播放视频')
  }
}

// 节流保存播放进度
const saveProgressThrottled = () => {
  if (!videoInfo.value || currentTime.value === lastSavedTime.value) return
  
  // 每5秒保存一次进度，或者播放进度变化超过5秒
  if (Math.abs(currentTime.value - lastSavedTime.value) >= 5) {
    console.log('自动保存播放进度:', currentTime.value)
    saveProgress()
  }
}

// 保存播放进度
const saveProgress = async () => {
  if (!videoInfo.value || duration.value === 0) return
  
  // 清除之前的定时器
  if (progressSaveTimer.value) {
    clearTimeout(progressSaveTimer.value)
  }
  
  // 延迟保存，避免频繁请求
  progressSaveTimer.value = setTimeout(async () => {
    try {
      await fileManagerApi.saveVideoProgress({
        fileId: videoInfo.value!.id,
        currentTime: currentTime.value,
        duration: duration.value
      })
      lastSavedTime.value = currentTime.value
      console.log('播放进度已保存:', currentTime.value)
    } catch (error) {
      console.warn('保存播放进度失败:', error)
    }
  }, 1000) // 1秒延迟
}

// 清除播放进度 - 通过保存进度为0来实现清除
const clearProgress = async () => {
  if (!videoInfo.value) return
  
  try {
    await fileManagerApi.saveVideoProgress({
      fileId: videoInfo.value.id,
      currentTime: 0,
      duration: duration.value
    })
    console.log('播放进度已清除')
  } catch (error) {
    console.warn('清除播放进度失败:', error)
  }
}

// 播放下一个随机视频
const playNextRandomVideo = () => {
  if (!hasVideoList.value) return
  
  // 从视频列表中排除当前正在播放的视频
  const availableVideos = videoList.value.filter(video => 
    video.id !== videoInfo.value?.id
  )
  
  if (availableVideos.length === 0) return
  
  // 生成随机索引
  const randomIndex = Math.floor(Math.random() * availableVideos.length)
  const nextVideo = availableVideos[randomIndex]
  
  // 延迟3秒播放下一个视频，给用户一些准备时间
  setTimeout(() => {
    ElMessage.info(`自动播放下一个视频: ${nextVideo.fileName}`)
    // 在当前窗口跳转到下一个视频（无论是新窗口还是当前页面）
    router.push({
      name: 'VideoPlayer',
      params: { id: nextVideo.id },
      query: {
        random: 'true',
        videoList: JSON.stringify(videoList.value)
      }
    })
  }, 3000)
}

// 手动播放下一个视频
const playNextVideo = () => {
  playNextRandomVideo()
}

// 从 localStorage 读取存储的播放速度
function getStoredPlaybackSpeed(): number {
  try {
    const stored = localStorage.getItem(PLAYBACK_SPEED_KEY)
    if (stored) {
      const speed = parseFloat(stored)
      // 验证速度值的合法性（与加减速功能的范围保持一致：0.25-4.0）
      if (speed >= 0.25 && speed <= 4.0) {
        return speed
      }
    }
  } catch (error) {
    console.warn('读取播放速度设置失败:', error)
  }
  return 1.0 // 默认速度
}

// 保存播放速度到 localStorage
function savePlaybackSpeed(speed: number): void {
  try {
    localStorage.setItem(PLAYBACK_SPEED_KEY, speed.toString())
    console.log(`播放速度已保存: ${speed}x`)
  } catch (error) {
    console.warn('保存播放速度设置失败:', error)
  }
}

// 应用播放速度到视频元素
function applyPlaybackSpeed(): void {
  if (videoRef.value) {
    videoRef.value.playbackRate = playbackSpeed.value
    console.log(`已设置播放速度: ${playbackSpeed.value}x`)
  }
}

// 播放速度变化处理
const onPlaybackSpeedChange = () => {
  applyPlaybackSpeed()
  savePlaybackSpeed(playbackSpeed.value)
  ElMessage.success(`播放速度已设置为: ${playbackSpeed.value}x`)
}

// 减速（[ 键）
const decreasePlaybackSpeed = () => {
  if (!videoRef.value) return

  const newSpeed = Math.max(0.25, playbackSpeed.value - 0.25)
  if (newSpeed !== playbackSpeed.value) {
    playbackSpeed.value = parseFloat(newSpeed.toFixed(2))
    applyPlaybackSpeed()
    savePlaybackSpeed(playbackSpeed.value)
    ElMessage.success(`播放速度: ${playbackSpeed.value}x`)
  } else {
    ElMessage.warning('已达到最低速度 0.25x')
  }
}

// 加速（] 键）
const increasePlaybackSpeed = () => {
  if (!videoRef.value) return

  const newSpeed = Math.min(4.0, playbackSpeed.value + 0.25)
  if (newSpeed !== playbackSpeed.value) {
    playbackSpeed.value = parseFloat(newSpeed.toFixed(2))
    applyPlaybackSpeed()
    savePlaybackSpeed(playbackSpeed.value)
    ElMessage.success(`播放速度: ${playbackSpeed.value}x`)
  } else {
    ElMessage.warning('已达到最高速度 4.0x')
  }
}

// 返回文件列表
const goBack = () => {
  // 暂停视频
  if (videoRef.value) {
    videoRef.value.pause()
  }
  
  // 检查是否在新窗口中打开，如果是则关闭窗口，否则跳转回文件管理器
  if (window.opener) {
    // 在新窗口中打开的，关闭当前窗口（会触发beforeunload事件自动保存进度）
    window.close()
  } else {
    // 直接访问的，跳转回文件管理器（会触发组件卸载自动保存进度）
    router.push('/file-manager')
  }
}
</script>

<style scoped>
.video-player-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--el-bg-color-page);
}

/* 顶部导航 */
.video-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex-shrink: 0;
  margin-right: 20px;
}

.header-center {
  flex: 1;
  text-align: center;
}

.video-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-right {
  flex-shrink: 0;
  margin-left: 20px;
}

/* 视频内容区域 */
.video-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.video-wrapper {
  position: relative;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto 24px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-player {
  width: 100%;
  height: auto;
  max-height: 70vh;
  display: block;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  min-height: 300px;
}

.loading-overlay .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #f56c6c;
  font-size: 16px;
  min-height: 300px;
}

.error-overlay .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 视频信息面板 */
.video-info-panel {
  max-width: 1200px;
  margin: 0 auto;
}

/* 刮削信息 */
.scraper-info {
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-color-success-light-9) 100%);
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 20px;
  border: 1px solid var(--el-border-color-lighter);
}

.scraper-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 16px;
  line-height: 1.4;
}

.scraper-meta {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.meta-tag {
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}

.video-info {
  background: var(--el-fill-color-light);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-item .label {
  font-weight: 500;
  color: var(--el-text-color-regular);
  min-width: 80px;
}

.info-item .value {
  color: var(--el-text-color-primary);
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 播放控制面板 */
.player-controls {
  background: var(--el-fill-color-light);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.time-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.time-display {
  font-size: 18px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  font-family: 'Courier New', monospace;
}

.skip-time-setting {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.skip-time-setting .label,
.skip-time-setting .unit {
  color: var(--el-text-color-secondary);
  font-family: inherit;
}

.controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
}

.playback-speed-setting {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  margin-left: 16px;
}

.playback-speed-setting .label {
  color: var(--el-text-color-secondary);
  font-family: inherit;
  min-width: auto;
  margin-right: 0;
}

/* 快捷键说明 */
.shortcuts-info {
  text-align: center;
  padding: 12px;
  background: var(--el-fill-color-lighter);
  border-radius: 6px;
}

/* 无视频状态 */
.no-video {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .video-header {
    padding: 12px 16px;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .header-left,
  .header-right {
    margin: 0;
  }
  
  .header-center {
    order: -1;
    width: 100%;
    text-align: left;
  }
  
  .video-title {
    font-size: 16px;
  }
  
  .video-content {
    padding: 16px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .time-info {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .time-display {
    text-align: center;
  }
  
  .controls {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .playback-speed-setting {
    margin-left: 0;
    margin-top: 8px;
  }
}

@media (max-width: 480px) {
  .controls {
    flex-direction: column;
    gap: 12px;
    width: 100%;
  }
  
  .controls .el-button {
    width: 100%;
    justify-content: center;
  }
  
  .playback-speed-setting {
    justify-content: center;
    width: 100%;
  }
}

/* 深色模式适配 */
.dark .scraper-info {
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(103, 194, 58, 0.1) 100%);
  border-color: var(--el-border-color-darker);
}

.dark .scraper-title {
  color: var(--el-color-primary-light-3);
}

.dark .video-info {
  background: var(--el-fill-color-dark);
}

.dark .player-controls {
  background: var(--el-fill-color-dark);
}

.dark .shortcuts-info {
  background: var(--el-fill-color-darker);
}
</style>